<?php defined('SYSPATH') or die('No direct script access.');

class Model_Api_V2_Together extends Model
{

    /**
     * 获取正在拼团的列表
     * @param $together
     * @param $start
     * @param $limit
     * @return array|mixed
     */
    public static function get_pending_join_list($together, $start = null, $limit = null)
    {
        $join_list = array();
        if ($together['status'] == Model_Together::TOGETHER_STATUS_PENDING && $together['gather_together_is_open']) {
            $params = array(
                'together_id' => $together['id'],  // 拼团id
                'status' => Model_Together_Join::JOIN_STATUS_PENDING,
                'field' => 'id,member_id,expire_time,together_num',
                'order_field' => 'addtime',
                'desc' => 'asc'
            );
            if ($start != null && $limit != null) {
                $params['start'] = $start;
                $params['limit'] = $limit;
            }
            $join_list_res = Model_Together_Join::get_list($params);
            $join_list     = $join_list_res['lists'];
            if (!empty($join_list)) {
                $member_ids = Arr::pluck($join_list, 'member_id');
                $members    = Model_Together_Join::get_members_info($member_ids);
                foreach ($join_list as &$v) {
                    $nickname   = '未知';
                    $header_pic = Common::member_nopic();
                    if (isset($members[$v['member_id']])) {
                        $nickname   = $members[$v['member_id']]['nickname'] ?: $nickname;
                        $header_pic = $members[$v['member_id']]['litpic'] ?: $header_pic;
                    }
                    $v['join_id']           = $v['id'];
                    $v['together_id']       = $together['id'];
                    $v['nickname']          = $nickname;
                    $v['header_pic']        = Model_Api_V2_System::uniapp_img($header_pic, 80, 80);
                    $remaining_seconds      = bcsub($v['expire_time'], time(), 0);
                    $v['remaining_seconds'] = max($remaining_seconds, 0) * 1000;
                    $together_num           = Model_Together_Order::count_join_num($v['id']);
                    $need_num               = bcsub($v['together_num'], $together_num, 0);
                    $v['need_num']          = max(intval($need_num), 0);
                    // 当前已拼次数
                    $params               = array(
                        'member_id' => $v['member_id'],
                        'status' => Model_Together_Order::STATUS_FINISHED,
                    );
                    $join_num             = Model_Together::get_join_total_number($params);
                    $v['member_join_num'] = $join_num > 0 ? St_String::numToWord($join_num) : '';
                    unset($v['member_id']);
                    unset($v['id']);
                }
            }
        }
        return $join_list;
    }

    /**
     * 格式化产品图片列表
     * @param $type_id
     * @param $product_id
     * @return array
     * @throws Exception
     */
    public static function get_pic_list($type_id, $product_id)
    {
        $pic_list = Model_Together_Product::get_pic_list($type_id, $product_id);
        $pic_list = !empty($pic_list) ? $pic_list : array(array(Common::nopic()));
        $data     = array();
        foreach ($pic_list as $v) {
            if (isset($v[0])) {
                list($url, $name) = $v;
                $data[] = array(
                    'url' => Model_Api_V2_System::uniapp_img($url, 375, 200),
                    'name' => $name ?: ''
                );
            }
        }
        return $data;
    }

    /**
     * 通过拼团id获取预定套餐信息
     * @param $together_id
     * @return array
     */
    public static function suit($together_id, $member_id = null)
    {
        $data = array();
        try {
            $together = self::check_together_booking($together_id, $member_id);
            // 查询预定套餐
            $data = Model_Together_Product::get_booking_suit($together);
        } catch (Exception $e) {
            // 记录错误日志
            $log = array(
                'title' => '通过拼团id获取预定套餐信息',
                'together_id' => $together_id,
                'member_id' => $member_id,
                'message' => $e->getMessage(),
            );
            self::write_log($log);
            $data = [
                'err_msg' => $e->getMessage()
            ];
        }
        return $data;
    }

    /**
     * 获取价格日历
     * @param $together_id
     * @param $params
     * @return array
     */
    public static function get_price_calendar($together_id, $params = array())
    {
        $data = array();
        /**
         * @var $member_id int 会员id
         */
        extract($params);

        try {
            $member_id = isset($member_id) ? $member_id : '';
            $together  = self::check_together_booking($together_id, $member_id);

            // 查询预定套餐价格
            $data = Model_Together_Product::get_booking_price_data($together, $params);
        } catch (Exception $e) {
            // 记录错误日志
            $log = array(
                'title' => '通过拼团id获取价格日历',
                'together_id' => $together_id,
                'params' => $params,
                'message' => $e->getMessage(),
            );
            self::write_log($log);
        }
        return $data;
    }

    /**
     * 检查拼团是否可进行预订
     * @param $together_id
     * @param null $member_id
     * @return mixed
     * @throws Exception
     */
    public static function check_together_booking($together_id, $member_id = null)
    {
        if (!St_Functions::is_normal_app_install('together')) {
            throw new Exception('应用未安装');
        }

        $together = Model_Together::get_info($together_id);
        if (!$together || $together['is_show'] != 1) {
            throw new Exception('拼团不存在或已下架');
        }

        // 检查是否在可预订状态中
        $together_status = Model_Together::get_status($together);
        if ($together_status == Model_Together::TOGETHER_STATUS_WAIT) {
            throw new Exception('拼团未开始');
        }
        if ($together_status == Model_Together::TOGETHER_STATUS_END) {
            throw new Exception('拼团已结束');
        }

        // 检查可用库存
        $remaining_stock = Model_Together::get_remaining_stock($together);
        if ($remaining_stock <= 0) {
            throw new Exception('该拼团已售罄');
        }

        // 如果有会员id
        if ($member_id) {
            // 检查会员是否限制会员等级
            $allow_member_type = $together['allow_member_type'];
            if ($allow_member_type != 0) {
                $allow_member_type_arr = explode(',', $allow_member_type);
                $member_grade          = Model_Member::get_member_grade($member_id);
                St_Log::get_logger('debug/log')->debug('拼团会员等级检查', [$allow_member_type_arr, $member_grade]);
                if (!$member_grade || !in_array($member_grade['id'], $allow_member_type_arr)) {
                    throw new Exception('当前会员等级不支持预订');
                }
            }

            // 可预订次数
            $limit_member_order_num_is_open = $together['limit_member_order_num_is_open'];
            $limit_member_order_num         = $together['limit_member_order_num'];
            $total_join_num                 = Model_Together::get_join_total_number(array('member_id' => $member_id, 'together_id' => $together['id']));
            if ($limit_member_order_num_is_open && $total_join_num >= $limit_member_order_num) {
                throw new Exception('用户已达到最大拼团次数');
            }
        }

        return $together;
    }

    /**
     * 检查凑团是否可以继续预订
     * @param $join_id
     * @param $member_id
     * @return mixed
     * @throws Exception
     */
    public static function check_join_booking($join_id, $member_id)
    {
        $join = Model_Together_Join::get_info($join_id);

        // 检查是否在可预订状态中
        if (!$join) {
            throw new Exception('该凑团不存在');
        }

        // 判断凑团是否已经满了
        if ($join['status'] == Model_Together_Join::JOIN_STATUS_CREATED) {
            throw new Exception('凑团未开始');
        }
        if ($join['status'] == Model_Together_Join::JOIN_STATUS_SUCCESS) {
            throw new Exception('凑团已结束');
        }
        if ($join['status'] == Model_Together_Join::JOIN_STATUS_FAIL) {
            throw new Exception('拼团已结束_FAIL');
        }

        // 判断是否已经在团里面
        $join_order = Model_Together_Order::has_member_join_order($join_id, $member_id);
        if ($join_order) {
            throw new Exception('您已经参加该团');
        }
        return $join;
    }

    /**
     * 检查拼团是否可以进行预订
     * @param $together_id
     * @param $member_id
     * @param $params
     * @return array
     */
    public static function check_order_together($together_id, $member_id, $params = array())
    {
        /**
         * @var $ding_num int 下单人数
         * @var $join_id int 凑团id
         * @var $together_price_id int 拼团价格id
         */
        extract($params);
        try {

            $together = self::check_together_booking($together_id, $member_id);

            if ($together['limit_order_num_is_open'] == 1 && $ding_num > $together['limit_order_num']) {
                throw new Exception('预订数量超过限购数量');
            }

            if (isset($join_id) && $join_id) {
                $join = self::check_join_booking($join_id, $member_id);
                if ($join['together_id'] != $together_id) {
                    throw new Exception('凑团参数错误_JOIN_ID');
                }
            }

            // 如果是阶梯拼团需要判断together_price_id
            $price_id = '';
            if ($together['together_type'] == Model_Together::TOGETHER_TYPE_INSTEPS) {
                if (!isset($together_price_id) || !$together_price_id) {
                    throw new Exception('请选择拼团价格');
                }
                $price_id = $together_price_id;
            }

            // 检查是否存在报价
            $together_price = Model_Together_Price::get_price($together_id, $price_id);
            if (!$together_price) {
                throw new Exception('拼团还未设置价格');
            }

            // 预订折扣信息
            $discount_limit = self::make_allow_discount_type_data($together);

            $data = array(
                'together' => $together,
                'price' => $together_price,
            );

            $data['discount_limit'] = array();
            if (isset($discount_limit['type_arr'])) {
                $data['discount_limit'] = $discount_limit['type_arr'];
            }

            if (isset($join)) {
                $data['join'] = $join;
            }
            $res = array(
                'status' => true,
                'msg' => '',
                'data' => $data
            );
        } catch (Exception $e) {
            $res = array('status' => false, 'msg' => $e->getMessage());
        }

        return $res;
    }

    /**
     * 添加拼团订单
     * @param $together_data
     * @param $order_info
     * @return array|false[]
     */
    public static function add_order($together_data, $order_info)
    {
        try {

            if (!St_Functions::is_normal_app_install('together')) {
                throw new Exception('请先安装拼团插件');
            }

            $together = $together_data['together'];
            $price    = $together_data['price'];
            $join     = isset($together_data['join']) ? $together_data['join'] : null;

            // 添加拼团
            $join = Model_Together_Join::add_join($together, $price, $join, $order_info);
            if (!$join) {
                throw new Exception('添加拼团失败');
            }

            // 添加拼团订单
            $join_order = Model_Together_Order::add_order($join, $order_info);
            if (!$join_order) {
                throw new Exception('添加拼团订单失败');
            }
            $result = array(
                'status' => true,
                'data' => array(
                    'join' => $join->as_array(),
                    'join_order' => $join_order->as_array()
                )
            );
        } catch (Exception $e) {
            $result = array('status' => false, 'msg' => $e->getMessage());
        }
        return $result;
    }


    /**
     * 获取允许使用的优惠叠加类型
     * @param $together
     * @return array
     */
    public static function make_allow_discount_type_data($together)
    {

        $data = array();
        if ($together['allow_discount_type']) {
            $data['type_arr'] = explode(',', $together['allow_discount_type']);
            $detail           = array();
            sort($data['type_arr']);
            $allow_discount_types = Model_Together::get_allow_discount_types();
            foreach ($data['type_arr'] as $v) {
                if (isset($allow_discount_types[$v])) {
                    $detail[] = array(
                        'id' => $v,
                        'name' => $allow_discount_types[$v]
                    );
                }
            }
            $data['detail'] = $detail;
        }
        return $data;
    }

    /**
     * 获取参团的人员的信息
     * @param $join_id
     * @param $creator_member_id
     * @param $virtual_num int 模拟会员人数
     * @return array
     */
    public static function get_join_members($join_id, $creator_member_id, $virtual_num = 0)
    {
        // 获取参团订单
        $order_members = Model_Together_Order::get_members($join_id);

        $member_ids = Arr::pluck($order_members['lists'], 'member_id');
        $members    = Model_Together_Join::get_members_info($member_ids);

        $join_members = array();
        foreach ($order_members['lists'] as $item) {
            $nickname   = '未知';
            $header_pic = Common::member_nopic();
            if (isset($members[$item['member_id']])) {
                $nickname   = $members[$item['member_id']]['nickname'] ?: $nickname;
                $header_pic = $members[$item['member_id']]['litpic'] ?: $header_pic;
            }
            $join_members[] = array(
                'is_creator' => $item['member_id'] == $creator_member_id,
                'nickname' => $nickname,
                'header_pic' => Model_Api_V2_System::uniapp_img($header_pic, 120, 120),
            );

            if ($virtual_num > 0) {
                for ($i = 0; $i < $virtual_num; $i++) {
                    $join_members[] = self::get_virtual_member();
                }
            }
        }
        return $join_members;
    }

    /**
     * 获取模拟会员
     * @return array
     */
    private static function get_virtual_member()
    {
        $header_pic = Common::member_nopic();
        return array(
            'is_creator' => false,
            'nickname' => '***',
            'header_pic' => Model_Api_V2_System::uniapp_img($header_pic, 120, 120),
        );
    }

    /**
     * 检查拼团和产品是否匹配,并返回拼团数据
     * @param $together_id
     * @param $params
     * @return mixed
     * @throws Exception
     */
    public static function check_book_product($together_id, $params = array())
    {
        /**
         * @var $product_id
         * @var $suit_id
         */
        extract($params);

        $together = Model_Together::get_info($together_id);
        if (!$together) {
            throw new Exception('拼团不存在');
        }
        if (isset($product_id)) {
            if ($together['product_id'] != $product_id) {
                throw new Exception('拼团产品选择错误');
            }
        }
        if (isset($suit_id)) {
            if ($together['suit_id'] != $suit_id) {
                throw new Exception('拼团产品套餐选择有误');
            }
        }

        return $together;
    }

    // 写入拼团日志
    public static function write_log($data, $type = 'error')
    {
        $log_filename = Kohana::$config->load("api_log.together.{$type}");
        St_Log::write('API拼团日志', $data, $log_filename);
    }
}
